#coding=utf-8
from datetime import datetime as dt
import traceback
import urllib

from apps.domain.models import *
from libs import pywhois
import mechanize
from utils.uthread import timeout

@timeout(120)
def scan_domain(domain, name=None):
    if not domain:
        domain = DBSession.query(Domain).filter(Domain.name == name).first()
    try:
        w = pywhois.whois(domain.name)
        if len(w.status) == 0:
            domain.status = 'Available'
        else:
            for i in w.attrs():
                dates = list(set(getattr(w, i)))
                if i.find('_date') >= 0:
                    if len(dates) == 0:
                        setattr(domain, i, None)
                        continue
                    _date = dates[0].strip() if dates else None
                    result = False
                    _date_len = len(_date.split(' '))
                    if _date_len == 1:
                        try:
                            _date = dt.strptime(_date, '%d-%b-%Y')
                            result = True
                        except:
                            pass
                        if not result:
                            try:
                                _date = dt.strptime(_date[0:10], '%Y-%m-%d')
                                result = True
                            except:
                                pass
                    elif _date_len == 2:
                        try:
                            _date = dt.strptime(_date[0:10], '%Y-%m-%d')
                            result = True
                        except:
                            pass
                    elif _date_len == 3:
                        try:
                            _date = dt.strptime(_date.split(' ')[0], '%d-%b-%Y')
                            result = True
                        except:
                            pass
                    else:
                        try:
                            _dtstrs = _date.split(' ')
                            _dtstr = '%s %s %s' % (_dtstrs[1], _dtstrs[2], _dtstrs[5],)
                            _date = dt.strptime(_dtstr, '%b %d %Y')
                            result = True
                        except:
                            pass
                    if i == 'expiration_date' and not result:
                        print 'error expiration_date(len %s): %s' % (_date_len, _date)
                    setattr(domain, i, _date)
                else:
                    _dates = [j.strip() for j in dates]
                    setattr(domain, i, ' | '.join(_dates))
        if domain.expiration_date and domain.emails and (dt.today() - domain.expiration_date).days > 30:
            DomainExpiredEmail.create(domain.emails)
        DBSession.merge(domain)
        DBSession.flush()
        print 'ok whois'
        return domain
    except:
        lines = traceback.format_exc().splitlines()
        print 'error whois: %s' % lines[-1]
        return None

@timeout(120)
def scan_my_namecom():
    domains = []
    br = mechanize.Browser()
    br.open('http://www.name.com/name')
    br.select_form(nr=1)
    p1 = br.open('https://manage.name.com/account/login_u.php?redir_location=/', urllib.urlencode({'acct_name':'weber110@gmail.com', 'password':'5rihaigong'}))
    p2 = br.open('https://manage.name.com/account/domain-nabber')
    r2 = p2.read()
    index = None
    for idx, i in enumerate(r2.split('\n')):
        if i.find('pendingDeleteData.addRows([') > 0:
            index = idx + 1
    if index:
        c2 = r2.split('\n')[index]
        c21 = c2[0:len(c2)-4].strip().split("\'")
        for i in c21:
            j = i.strip().split('.')
            if(len(j) == 2):
                try:
                    ['cc', 'com', 'net', 'co'].index(j[1])
                    domains.append(i)
                except:
                    pass
    print '#' * 10, 'my name.com domains'
    print domains
    return domains

@timeout(120)
def scan_namecom(domain, name=None, write_file=False):
    if not domain:
        domain = DBSession.query(Domain).filter(Domain.name == name).first()
    _domain, _appendix = domain.name.split('.')
    domainname = '%s-%s' % (_domain, _appendix)
    br = mechanize.Browser()
    file_map = {}
    try:
        br.open('https://www.name.com/name')
        br.select_form(nr=1)
        br['domain'] = domain.name
        p1 = br.submit()
        r1 = p1.read()
        if write_file:
            file_map['%s.xml' % (_domain)] = r1.encode('utf-8')
        search_id = ''
        for i in r1.split('\n'):
            if i.find('window.search_id = ') >= 0:
                search_id = i[22:len(i)-2]
        print 'search_id: %s' % search_id
        def ajax_search(chunk_id=None, cycle=0):
            if cycle < 10:
                cycle += 1
                page = None
                if(chunk_id):
                    page = br.open('http://manage.name.com/name/ajax_chunk_taco', urllib.urlencode({'chunk_id':chunk_id}))
                else:
                    page = br.open('http://manage.name.com/name/ajax_search', urllib.urlencode({'search_id':search_id}))
                r2 = unicode(page.read(), 'utf-8')
                if len(r2) == 275 or len(r2) == 239:
                    print 'error namecom: %s byte' % len(r2)
                else:
                    try:
                        if write_file:
                            file_map['%s_%s.xml' % (_domain, cycle)] = r2.encode('utf-8')
                    except:
                        print traceback.print_exc()
                    if r2.find("<![CDATA[ <div class='cart-item pb-tld hover  %s-" % domainname) >= 0:
                        c1 = r2.split("<![CDATA[ <div class='cart-item pb-tld hover  %s-" % domainname)[1].split(' ')[1].split('\'')[0]
                        domain.backorder = c1
                        DBSession.merge(domain)
                        DBSession.flush()
                        print 'backorder: %s' % domain.backorder
#                    if r2.find('<html select="#%s" >' % domainname) >= 0:
#                        c1 = r2.split('<html select="#%s" >' % domainname)[1]
#                        print 'backorder: %s (%s times)' % (c1[13:c1.find('>')-1], cycle)
#                        domain.backorder = c1[13:c1.find('>')-1]
#                        DBSession.merge(domain)
                    elif r2.find('<chunkTaco arg1="') >= 0:
                        c1 = r2.split('<chunkTaco arg1="')[1]
                        print 'chunk_id: %s' % c1[0:c1.find('"')]
                        ajax_search(c1[0:c1.find('"')], cycle)
                    else:
                        print 'search again'
                        ajax_search(cycle=cycle)
            else:
                print 'error namecom: more than 10 times'
                if write_file:
                    for k, v in file_map.iteritems():
                        f1 = open(k, 'wb')
                        f1.write(v)
                        f1.close()

        ajax_search()
        return domain
    except:
        lines = traceback.format_exc().splitlines()
        print 'error namecom: %s' % lines[-1]
        return None